package com.twu.biblioteca;

import com.twu.exception.ShelfException;

import java.util.ArrayList;
import java.util.HashMap;

public class MovieShelf {
    private final HashMap<Movie, Customer> lentMovies;
    private ArrayList<Movie> movies;

    public MovieShelf(HashMap<Movie, Customer> lentMovies) {
        this.movies = new ArrayList<Movie>();
        this.lentMovies = lentMovies;
    }

    public boolean containsExact(Movie movie) {
        if (movies.contains(movie)) {
            return true;
        }
        return false;
    }

    public void add(Movie movie) throws ShelfException {
        if (movies.contains(movie)) {
            throw new ShelfException(LibraryConstants.MOVIE_IN_SHELF);
        }
        for (Movie thisMovie : movies) {
            if (thisMovie.number() == movie.number()){
                throw new ShelfException(LibraryConstants.MOVIE_WITH_NUMBER);
            }
        }
        movies.add(movie);
    }

    public boolean containsSimilar(Movie movie) {
        for (Movie movieInList : movies) {
            if (movieInList.title().equals(movie.title())) {
                return true;
            }
        }
        return false;
    }

    public Movie fetch(String title) throws ShelfException {
        for (Movie movieInList : movies) {
            if (movieInList.title().equals(title) && !lentMovies.containsKey(movieInList)) {
                return movieInList;
            }
        }
        throw new ShelfException(LibraryConstants.UNSUCCESSFUL_MOVIE_CHECKOUT_MSG);
    }

    public Movie returningMovie(int number) throws ShelfException {
        for (Movie movieInList : movies) {
            if (movieInList.number()==number && lentMovies.containsKey(movieInList)) {
                return movieInList;
            }
        }
        throw new ShelfException(LibraryConstants.UNSUCCESSFUL_MOVIE_RETURN_MSG);
    }

    public String movies() {
        String movieString = LibraryConstants.EMPTY_STRING;
        for (Movie movie : movies) {
            if (!lentMovies.containsKey(movie)) {
                movieString += movie.title() + LibraryConstants.NEW_LINE;
            }
        }
        if (movieString.isEmpty()) {
            movieString += LibraryConstants.ALL_MOVIES_LENT_OUT_MSG;
        }
        return movieString;
    }
}
